﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using Utility.Math;

namespace Utility.Inspector
{
	public class GUIPanScope : IDisposable
	{
		static float h_windowTab = 22;

		Matrix4x4 m_saved;

		public Rect ClipRect { get; private set; }

		public static GUIPanScope Begin (Rect rect_canvas, float scale)
		{
			var scope = new GUIPanScope ();
			scope.m_saved = GUI.matrix;

			GUI.EndGroup ();//end unity group to break clipping

			Rect rect_clip = rect_canvas.ShiftUp (h_windowTab).Scale (1 / scale);
			GUI.BeginGroup (rect_clip);

			Matrix4x4 m_window = Matrix4x4.Translate (new Vector2 (rect_canvas.xMin, rect_canvas.yMin + h_windowTab));
			Matrix4x4 m_scale = Matrix4x4.Scale (new Vector3 (scale, scale, 1));
			GUI.matrix = m_window * m_scale * m_window.inverse * GUI.matrix;

			scope.ClipRect = rect_clip;
			return scope;
		}

		public void Dispose ()
		{
			GUI.matrix = m_saved;
			GUI.EndGroup ();
			GUI.BeginGroup (new Rect (0, h_windowTab, Screen.width, Screen.height));//resume unity group
		}

	}
}